package com.ixc.test;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import jcifs.smb.SmbException;
import jcifs.smb.SmbFile;
import jcifs.smb.SmbFileInputStream;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;

public class LastViewActivity extends Activity {
	private static final String TAG = "ViewActivity";
	private static final boolean DBG = BuildConfig.DEBUG;

	private static final int READ_FILE_OK = 1;
	private static final int READ_FILELIST_OK = 2;
	private static final int SLIDE_TIMER = 3;
	private static final int REFRESH_TIMER = 4;
	private static final int NO_PICS = 5;

	private static final long SHOW_TIME = 5700l;
	private static final long SLIDE_TIME = 6000l;

	private static final String USERNAME = "wkwk";
	private static final String PASSWORD = "12341234";
//	private static final String USERNAME = "";
//	private static final String PASSWORD = "";
	// private static final String DIR_PATH = "192.168.1.233/xnptestphoto/";
	private static final String DIR_PATH = "192.168.1.133/photo/";

	private List<String> currentFileList;
	private List<String> allFileList;

	private Bitmap mBitmap1 = null;
	private Bitmap mBitmap2 = null;
	private Bitmap mBitmapBuff = null;
	private ImageView mImageView;

	private static final int IMG_NO_READ = 0;
	private static final int IMG_READING = 1;
	private static final int IMG_READ_OK = 2;
	private int mIsReadOK = IMG_NO_READ;

	private Timer mTimer;
	private SlideTimerTask mSlideTask;
	private RefreshTimerTask mRefreshTask;

	private Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case NO_PICS:{
//				mImageView.setImageResource(R.drawable.blood);
				break;
			}
			case READ_FILE_OK: {
				mIsReadOK = IMG_READ_OK;
				break;
			}
			case READ_FILELIST_OK: {
				break;
			}
			case REFRESH_TIMER: {
				initFileList();
				break;
			}
			case SLIDE_TIMER: {
				if(IMG_READ_OK == mIsReadOK) {

					if(mBitmapBuff != null){
						if(mBitmap1 == null){
							mBitmap1 = mBitmapBuff.copy(Bitmap.Config.RGB_565, false);
							mImageView.setImageBitmap(mBitmap1);
							if (mBitmap2 != null) {
								mBitmap2.recycle();
								mBitmap2 = null;
								System.gc();
							}
						}else if(mBitmap2 == null){
							mBitmap2 = mBitmapBuff.copy(Bitmap.Config.RGB_565, false);
							mImageView.setImageBitmap(mBitmap2);
							if (mBitmap1 != null) {
								mBitmap1.recycle();
								mBitmap1 = null;
								System.gc();
							}
						}
						
						
						mIsReadOK = IMG_NO_READ;
					}
				}

				String readFileName = "";
				double index = Math.random();
				if (currentFileList.isEmpty()) {
					if (!allFileList.isEmpty()) {
						readFileName = allFileList
								.get((int) (index * allFileList.size()));
					}
				} else {
					readFileName = currentFileList
							.get((int) (index * currentFileList.size()));
				}

				if(!readFileName.isEmpty() && mIsReadOK == IMG_NO_READ){
					Thread thread = new getImageThread(readFileName);
					thread.start();
				}
				break;
			}
			default:
				break;
			}
			super.handleMessage(msg);
		}
	};

	class getImageThread extends Thread{
		private String fileName;
		public getImageThread(String url){
			fileName = url;
		}
		@Override
		public void run() {
			// TODO Auto-generated method stub
			getImage(fileName);
		}
	}

	class SlideTimerTask extends TimerTask {
		@Override
		public void run() {
			// TODO Auto-generated method stub
//			if (DBG)
//				Log.i(TAG, "SLIDE_TIMER...");
			Message message = new Message();
			message.what = SLIDE_TIMER;
			mHandler.sendMessage(message);
		}

	};

	class RefreshTimerTask extends TimerTask {
		@Override
		public void run() {
			// TODO Auto-generated method stub
			if (DBG)
				Log.i(TAG, "REFRESH_TIMER...");
			Message message = new Message();
			message.what = REFRESH_TIMER;
			mHandler.sendMessage(message);
		}

	};

	private void getImage(String fileName) {
		SmbFile smbFile;
		try {
			mIsReadOK = IMG_READING;
			smbFile = new SmbFile(fileName);

			InputStream imageStream = new SmbFileInputStream(smbFile);
			if (mBitmapBuff != null) {
				mBitmapBuff.recycle();
				mBitmapBuff = null;
				System.gc();
			}
			BitmapFactory.Options options = new BitmapFactory.Options();
			options.inPurgeable = true;
			options.inPreferredConfig = Bitmap.Config.RGB_565;
			options.inSampleSize = 2;
			// options.inNativeAlloc = true;
			mBitmapBuff = BitmapFactory
					.decodeStream(imageStream, null, options);
			imageStream.close();
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SmbException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			if(mBitmapBuff == null){
				mIsReadOK = IMG_NO_READ;
			}
		}

		if(mBitmapBuff != null){
			Message message = new Message();
			message.what = READ_FILE_OK;
			mHandler.sendMessage(message);
		}

	}

	private void initFileList() {
		currentFileList.clear();
		allFileList.clear();

		Thread thread = new Thread(new Runnable() {
			@Override
			public void run() {
				if (DBG)
					Log.e(TAG, "initFileList");
				// TODO Auto-generated method stub
				try {
					String local = "";
					if (USERNAME.isEmpty()) {
						local = "smb://" + DIR_PATH;
					} else if (PASSWORD.isEmpty()) {
						local = "smb://" + USERNAME + "@" + DIR_PATH;
					} else {
						local = "smb://" + USERNAME + ":" + PASSWORD + "@"
								+ DIR_PATH;
					}

					SmbFile smbFile = new SmbFile(local);
					// 120628C156.JPG
					if (smbFile.isDirectory()) {
						long curTime = 0L;// = System.currentTimeMillis();
						String fileName = "";
						if(DBG) Log.e("FILE", "=======START==========");
						for (SmbFile file : smbFile.listFiles()) {
							if (file.toString().endsWith(".jpg")) {
//								allFileList.add(file.toString());

//								if (DBG)
//									Log.i(TAG,
//											"cur "
//													+ curTime
//													+ "!"
//													+ new Date(curTime)
//													+ "  file time"
//													+ file.createTime()
//													+ "!"
//													+ new Date(file
//															.createTime())
//													+ "!!!"
//													+ (curTime - file
//															.createTime())
//													+ SHOW_TIME);
								if (curTime < file.createTime()) {
									curTime =file.createTime();
									fileName = file.toString();
								}
								
							}
							// isSuccess = copyRemoteFile(file, localDirectory);
						}
						if(DBG) Log.e("FILE", "=======END==========");
						if(!fileName.isEmpty()){
							if(DBG) Log.w("FILE", "file name: " + fileName);
							currentFileList.add(fileName);
						}
					}
					// else if(smbFile.isFile()){
					// isSuccess = copyRemoteFile(smbFile, localDirectory);
					// }
					// InputStream imageStream = new
					// SmbFileInputStream(smbFile);
					// mBitmap = BitmapFactory.decodeStream(imageStream);
				} catch (MalformedURLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (SmbException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

				Message message = new Message();
				if(allFileList.isEmpty()){
					message.what = NO_PICS;
					mHandler.sendMessage(message);
				}else{
					message.what = READ_FILELIST_OK;
					mHandler.sendMessage(message);
				}
			}
		});
		thread.start();
	}

	protected void onDesdroy() {
		super.onDestroy();
		if (mTimer != null) {
			mTimer.cancel();
			mTimer = null;
		}

		if (mSlideTask != null) {
			mSlideTask.cancel();
			mSlideTask = null;
		}

		if (mRefreshTask != null) {
			mRefreshTask.cancel();
			mRefreshTask = null;
		}
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		getWindow().setFlags(
				WindowManager.LayoutParams.FLAG_FULLSCREEN
						| WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON,
				WindowManager.LayoutParams.FLAG_FULLSCREEN
						| WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);// ���ó�ȫ��ģʽ

//		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
		// û����
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE);
		
		getWindow().getDecorView().setSystemUiVisibility(View.STATUS_BAR_HIDDEN);
		setContentView(R.layout.activity_view);

		mImageView = (ImageView) this.findViewById(R.id.photoview);
		mImageView.setImageResource(R.drawable.bk110);

		currentFileList = new ArrayList<String>();
		allFileList = new ArrayList<String>();

		initFileList();

		mTimer = new Timer();
		mSlideTask = new SlideTimerTask();
		mRefreshTask = new RefreshTimerTask();

		mTimer.schedule(mSlideTask, SLIDE_TIME, SLIDE_TIME);
		mTimer.schedule(mRefreshTask, SHOW_TIME, SHOW_TIME);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_view, menu);
		return true;
	}

}
